package hsp.admin.app.base.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import hsp.admin.app.base.info.RoleInfo;
import hsp.admin.app.base.mapper.RoleMapper;
import hsp.admin.app.base.po.RoleAppRelationPO;
import hsp.admin.app.base.po.RolePO;
import hsp.admin.app.base.service.IRoleAppRelationService;
import hsp.admin.app.base.service.IRoleService;
import hsp.admin.util.SessionUtil;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.io.Serializable;
import java.util.List;

@Service
public class RoleServiceImpl extends ServiceImpl<RoleMapper, RolePO> implements IRoleService {

    private final SessionUtil sessionUtil;

    private final RoleMapper mapper;

    private final IRoleAppRelationService roleAppRelationService;


    @Autowired
    public RoleServiceImpl(
        SessionUtil sessionUtil,
        RoleMapper mapper,
        IRoleAppRelationService roleAppRelationService
    ){
        this.sessionUtil = sessionUtil;
        this.mapper = mapper;
        this.roleAppRelationService = roleAppRelationService;
    }

    @Transactional
    @Override
    public boolean removeById(Serializable id) {
        LambdaQueryWrapper<RoleAppRelationPO> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(RoleAppRelationPO::getRoleId, id);
        roleAppRelationService.remove(wrapper);

        return super.removeById(id);
    }

    @Override
    public List<RoleInfo> fetchInfo() {
        List<RolePO> list = fetchListByUserId(sessionUtil.getUserId());
        return list.stream().map(ele -> {
            RoleInfo info = new RoleInfo();
            BeanUtils.copyProperties(ele, info);
            return info;
        }).toList();
    }

    private List<RolePO> fetchListByUserId(long userId) {
        return mapper.selectListByUserId(userId);
    }

}
